<script>
export default {
  name: "AdoptionManage",
  data() {
    return {
      tableData: [],
      pageSize: 10,
      pageNum: 1,
      total: 0,
      keywords: '',
      centerDialogVisible: false,
      notifications: [],
      unreadCount: 0,
      notificationDialogVisible: false,
      form: {
        id: '',
        petNo: '',
        adopterNo: '',
        adoptTime: '',
        content: '',
        status: '',
        petName: '',
      },
      rules: {
        petNo: [{required: true, message: '请输入宠物编号', trigger: 'blur'}],
        petName: [{required: true, message: '请输入宠物名称', trigger: 'blur'}],
        adopterNo: [{required: true, message: '请输入领养者账号', trigger: 'blur'}],
        status: [{required: true, message: '请选择宠物状态', trigger: 'blur'}],
        adoptTime: [{required: true, message: '请选择领养时间', trigger: 'blur'}],
      }
    };
  },
  methods: {
    // 加载数据
    loadPost() {
      this.$axios.post(this.$httpUrl + '/adoption/listPageA', {
        pageSize: this.pageSize,
        pageNum: this.pageNum,
        param: {keywords: this.keywords}
      }).then(res => res.data).then(res => {
        if (res.code === 200) {
          this.tableData = res.data;
          this.total = res.total;
        } else {
          alert('获取数据失败')
        }
      });
    },
    // 新增/保存
    save() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.form.id) {
            this.doMod();
          } else {
            this.doSave();
          }
        } else {
          this.$message.error('请填写完整表单！');
          return false;
        }
      });
    },
    doMod() {//更新
      const formData = new FormData();
      formData.append('id', this.form.id);
      formData.append('petNo', Number(this.form.petNo));
      formData.append('petName', this.form.petName);
      formData.append('adopterNo', this.form.adopterNo);
      formData.append('status', Number(this.form.status));
      formData.append('adoptTime', this.formatDateTime(this.form.adoptTime) || '');
      this.$axios.post(this.$httpUrl + '/adoption/update', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }).then(res => res.data).then(res => {
        if (res.code === 200) {
          this.$message.success('更新成功！');
          this.centerDialogVisible = false;
          this.loadPost();
        } else {
          this.$message.error(res.data.msg || '更新失败！');
        }
      }).catch(error => {
        console.error('更新请求失败:', error);
        this.$message.error('请求异常，请检查控制台');
      });
    },
    doSave() {//新增
      const formData = new FormData();
      // 添加所有表单字段
      formData.append('id', this.form.id);
      formData.append('petNo', Number(this.form.petNo));
      formData.append('petName', this.form.petName);
      formData.append('adopterNo', this.form.adopterNo);
      formData.append('status', Number(this.form.status));
      formData.append('adoptTime', this.formatDateTime(this.form.adoptTime) || '');
      if (this.form.imageFile) {
        formData.append('imageFile', this.form.imageFile);
      }
      this.$axios.post(this.$httpUrl + '/adoption/save', formData, {
        headers: {
          'Content-Type': 'multipart/form-data' //设置FormData的Content-Type
        }
      }).then(res => res.data).then(res => {
        if (res.code === 200) {
          this.$message.success(' 新增成功！');
          this.centerDialogVisible = false;
          this.loadPost();
        } else {
          this.$message.error(res.data.msg || '新增失败！');
        }
      });
    },
    // 删除
    del(id) {//"删除"按钮方法
      this.$axios.get(this.$httpUrl + `/adoption/del?id=${id}`).then(res => {
        if (res.data.code === 200) {
          this.$message.success('删除成功！');
          this.loadPost();
        } else {
          this.$message.error('删除失败！');
        }
      }).catch(error => {
        console.error('删除请求失败:', error);
        this.$message.error('请求异常，请检查控制台');
      });
    },
    mod(row) {////"编辑"按钮方法:赋值到表单
      console.log(row)
      this.centerDialogVisible = true
      this.$nextTick(() => {
        this.form.id = row.id
        this.form.petNo = row.petNo
        this.form.petName = row.petName
        this.form.adopterNo = row.adopterNo
        this.form.adoptTime = row.adoptTime
        this.form.status = row.status
      })
    },
    resetParam() {
      this.keywords = ''
      this.loadPost()
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageNum = 1
      this.pageSize = val
      this.loadPost()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.pageNum = val
      this.loadPost()
    },
    add() {//打开表单
      this.loadPost();
      this.centerDialogVisible = true
      this.$nextTick(() => {
        this.resetForm();
      })
    },
    resetForm() {
      this.$refs.form.resetFields();
    },
    async loadNotifications() {
      const userId = this.$store.state.user.no;
      const res = await this.$axios.get(`/notification/listAdoption?userId=${userId}`);
      if (res.data.code === 200) {
        this.notifications = res.data.data.filter(n => n.status === 0);
        this.unreadCount = this.notifications.length;
        this.notificationDialogVisible = true;
      }
    },
    //处理通知
    async handleProcess(notification, applyStatus) {
      try {
        let reason;
        if (applyStatus === 2) { // 拒绝操作
          reason = prompt("请输入拒绝理由：");
          if (reason === null) { // 用户点击取消
            return; // 直接返回，不发送请求
          }
          if (reason.trim() === "") { // 用户未输入理由但点击确定
            this.$message.warning("拒绝理由不能为空");
            return;
          }
        } else { // 通过操作
          reason = "";
        }

        const res = await this.$axios.post(
            `/notification/processAdoption/${notification.id}`,
            {
              applyStatus: applyStatus, // 关键：传递 applyStatus
              reason: reason
            }
        );
        if (res.data.code === 200) {
          this.loadPost();
          this.loadNotifications();
          this.$message.success("操作成功");
        }
      } catch (error) {
        this.$message.error("处理失败：" + error.response?.data?.msg);
      }
    }
  },
  beforeMount() {
    this.loadPost();
  },
  mounted() {
    this.loadNotifications(); // 页面加载时检查通知
  }
}
</script>

<template>
  <div>
    <!-- 查询条件 -->
    <div style="border-bottom: 5px">
      <el-input v-model="keywords" placeholder="宠物编号/宠物名称/领养者..." suffix-icon="el-icon-search" style="width: 200px"
                @keyup.enter.native="loadPost"></el-input>
      <el-button type="primary" style="margin-left: 5px" @click="loadPost">查询</el-button>
      <el-button type="success" @click="resetParam">重置</el-button>
      <el-button type="primary" style="margin-left: 5px" @click="add">新增</el-button>
      <el-badge :value="unreadCount" :hidden="unreadCount === 0" style="margin-left: 10px" class="notification-badge">
        <el-button style="margin-left: 10px" @click="loadNotifications" class="el-icon-bell">新消息提醒</el-button>
      </el-badge>
    </div>

    <!-- 表格 -->
    <el-table :data="tableData" :header-cell-style="{background:'#d2bcad'}"
              border>
      <el-table-column prop="id" label="ID">
      </el-table-column>
      <el-table-column prop="petNo" label="宠物编号" />
      <el-table-column prop="petName" label="宠物名称" />
      <el-table-column prop="adopterNo" label="领养者账号" />
      <el-table-column prop="status" label="状态">
        <template slot-scope="{ row }">
          <el-tag :type="row.status === 200 ? 'success' : 'danger'">
            {{ row.status === 200 ? '健康' : '疾病' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="adoptTime" label="领养时间" />
      <el-table-column label="操作">
        <template slot-scope="{ row }">
          <el-button size="small" type="primary" @click="mod(row)">编辑</el-button>
          <el-popconfirm
              confirm-button-text='好的'
              confirm-button-type="warning"
              cancel-button-text='不用了'
              icon="el-icon-info"
              icon-color="red"
              title="该操作不可逆,确定删除吗? "
              @confirm="del(row.id)"
              style="margin-left: 5px">
            <el-button slot="reference" size="small" type="danger" >删除</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNum"
        :page-sizes="[10, 15, 20, 25]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next"
        :total="total"
    />

    <!-- 表单弹窗 -->
    <el-dialog title="提示"
               :visible.sync="centerDialogVisible"
               width="30%"
               center>
      <el-form :model="form" :rules="rules" ref="form">
        <el-form-item label="宠物编号" prop="petNo">
          <el-input v-model="form.petNo" />
        </el-form-item>
        <el-form-item label="宠物名称" prop="petName">
          <el-input v-model="form.petName" />
        </el-form-item>
        <el-form-item label="领养者账号" prop="adopterNo">
          <el-input v-model="form.adopterNo" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="form.status">
            <el-option label="健康" :value="200" />
            <el-option label="疾病" :value="400" />
          </el-select>
        </el-form-item>
        <el-form-item label="领养时间">
          <el-date-picker
              v-model="form.adoptTime"
              type="datetime"
              placeholder="选择日期时间"
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="centerDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="save">确定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="待处理领养申请" :visible.sync="notificationDialogVisible">
      <el-table :data="notifications">
        <el-table-column prop="content" label="内容"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="success" @click="handleProcess(scope.row, 1)">通过</el-button>
            <el-button type="danger" @click="handleProcess(scope.row, 2)">拒绝</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>